package ch.sv7.tool.dbmanager.db.ant;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

import ch.sv7.tool.codec.Codecs;

public class DecodeBase64 extends Task {

	private String source;

	private String target;

	public DecodeBase64() {
	}

	public void execute() throws BuildException {
		if (getSource() == null || getSource().trim().length() == 0)
			throw new BuildException("Invalid source file");
		if (getTarget() == null || getTarget().trim().length() == 0)
			throw new BuildException("Invalid target file");
		File src = new File(getSource());
		if (!src.canRead() || !src.isFile())
			throw new BuildException("Unable to read from file " + src);
		File dest = new File(getTarget());
		if (dest.exists() && !dest.canWrite())
			throw new BuildException("Unable to write to file " + src);
		int size = (int) src.length();
		byte buffer[] = new byte[size];
		try {
			DataInputStream dis = new DataInputStream(new FileInputStream(getSource()));
			dis.readFully(buffer);
			dis.close();
			byte result[] = Codecs.base64Decode(buffer);
			DataOutputStream dos = new DataOutputStream(new FileOutputStream(getTarget()));
			dos.write(result);
			dos.close();
		} catch (FileNotFoundException e) {
			throw new BuildException("FileNotFoundException " + e.getMessage());
		} catch (IOException e) {
			throw new BuildException("IOException " + e.getMessage());
		}
	}

	public String getSource() {
		return source;
	}

	public String getTarget() {
		return target;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public void setTarget(String target) {
		this.target = target;
	}
}
